
#include "ctl.h"


int ctl_connect(int* sock){
  struct sockaddr_in addr;

  *sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if(*sock == -1){
      return -1;
  }

  // Устанавливает MAX число SYN-запросов для CONNECT
  set_connect_syn_max(*sock);

  addr.sin_family = AF_INET;
  addr.sin_port = htons(CTL_SERVER_PORT);
  addr.sin_addr.s_addr = inet_addr(SERVER_IP);
  //addr.sin_addr.s_addr = htonl(INADDR_ANY);

  if(connect(*sock, (struct sockaddr*) &addr, sizeof(addr)) == -1)
      return -1;

  enable_keepalive(*sock);

  return 0;
}

int ctl_con_check(int sock){
    int err_buf = 0;
    //fail_check(recv(sock, &err_buf, sizeof(err_buf), MSG_ERRQUEUE | MSG_DONTWAIT) == -1);
    if(recv(sock, &err_buf, sizeof(err_buf), MSG_PEEK | MSG_DONTWAIT) != -1)
        return -1;
    errno = 0;
    return 0;
}
int ctl_con_close(int sock){
    if(close(sock) == -1)
        return -1;
    return 0;
}

void set_connect_syn_max(int sock){
  int synRetries = 1;
  setsockopt(sock, IPPROTO_TCP, TCP_SYNCNT, &synRetries, sizeof(synRetries));
}
